/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.common.configuration;

import com.inspur.edp.lcm.metadata.api.ConfigData.gspproject.ProjectConfiguration;
import com.inspur.edp.lcm.metadata.common.Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * gsp工程配置文件加载器
 * @author zhongchq
 * @since 1.0
 */
public class GspProjectConfigurationLoader {
    private static final String FILE_NAME = "config/platform/common/lcm_gspprojectextend.json";
    private static final String SECTION_NAME = "ProjectConfiguration";
    private String absoluteFilePath;
    private List<ProjectConfiguration> gspProjectConfigurations;

    /**
     * @param
     * @return java.util.List<com.inspur.gsp.lcm.metadata.entity.ProjectConfiguration>
     * @throws
     * @author zhongchq
     * @description 类初始化时反序列化Json到实体
     * @date 15:40 2019/7/23
     **/
    protected List<ProjectConfiguration> loadGspProjectConfigurations() {
        try {
            if (CollectionUtils.isEmpty(gspProjectConfigurations)) {
                gspProjectConfigurations = MetadataServiceHelper.getConfigurationList(getAbsoluteFilePath(), SECTION_NAME, ProjectConfiguration.class);
            }
            return gspProjectConfigurations;
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件失败：" + getAbsoluteFilePath(), e);
        }
    }

    protected ProjectConfiguration getGspProjectConfigurationData(String typeName) {
        loadGspProjectConfigurations();
        if (gspProjectConfigurations != null && gspProjectConfigurations.size() > 0) {
            for (ProjectConfiguration data : gspProjectConfigurations) {
                if (data.getCommonConfigData().getTypeCode().equalsIgnoreCase(typeName)) {
                    return data;
                }
            }
        }
        return null;
    }

    private String getAbsoluteFilePath() {
        if (StringUtils.isEmpty(absoluteFilePath)) {
            absoluteFilePath = Utils.getAbsoluteConfigFilePath(FILE_NAME);
        }
        return absoluteFilePath;
    }
}
